package java01;

import org.junit.Test;

import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;

public class JavaReflect extends Person {

    @Override
    public Person clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Test
    public void reflectTest01(){
        ArrayList<Object> list = new ArrayList<>();
        for(int i=0;i<20;++i){
            list.add(i);
        }
        list.add(new JavaType());
        System.out.println(new ObjectAnalyzer().toString(list));
    }

    public static Object reflectArrayTest(Object a,int newLength){
        //创建一个通用的数组拷贝器就像Arrays.copyOf一样，整形数组可以被转换成Object，但不能被转换成Object[]
        Class<?> cl = a.getClass();//获取的是数组
        if(!cl.isArray()) return null;
        Class<?> componentType = cl.getComponentType();//获取数组中的类型
        int length = Array.getLength(a);
        Object newArray = Array.newInstance(componentType, Math.min(length,newLength));
        System.arraycopy(a,0,newArray,0,Math.min(length,newLength));
        return newArray;
    }

    @Test
    public void reflectStaticTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class<Math> mathClass = Math.class;
        Method sqrt = mathClass.getMethod("sqrt", double.class);
        Object invoke = sqrt.invoke(null, 16);//静态方法调用第一个参数为空
        System.out.println(invoke);
    }

    public static void main(String[] args) {
        int[] newInt = (int[]) reflectArrayTest(new int[]{1, 4, 6, 73, 5, 3, 2}, 10);
        System.out.println(Arrays.toString(newInt));
    }
}
